#include "board.h"
#include <rtdevice.h>
#include <rtdef.h>

typedef struct
{
    struct rt_i2c_bus_device busdev;
    I2C_TypeDef *i2c;
} di2c_t;

static void iic1_init(void)
{
    GPIO_InitTypeDef GPIO_InitStructure;
    I2C_InitTypeDef I2C_InitStructure;
    RCC_ClocksTypeDef rcc_clocks;

    /* GPIO Peripheral clock enable */
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
    RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);
    /* Reset I2Cx IP */
    RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C1, ENABLE);
    /* Release reset signal of I2Cx IP */
    RCC_APB1PeriphResetCmd(RCC_APB1Periph_I2C1, DISABLE);

    /*I2C1 configuration*/
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_I2C1); //注意，此处不能合并写成GPIO_PinSource6|GPIO_PinSource7
    GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_I2C1);

    //PB6: I2C1_SCL  PB7: I2C1_SDA
    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6 | GPIO_Pin_7;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
    GPIO_Init(GPIOB, &GPIO_InitStructure);

    /* I2C Struct Initialize */
    I2C_DeInit(I2C1);
    I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;
    I2C_InitStructure.I2C_DutyCycle = I2C_DutyCycle_2;
    I2C_InitStructure.I2C_OwnAddress1 = 0x00;
    I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
    I2C_InitStructure.I2C_ClockSpeed = 100000;
    I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
    I2C_Init(I2C1, &I2C_InitStructure);

    /* I2C Initialize */
    I2C_Cmd(I2C1, ENABLE);
}

static int iic_send(I2C_TypeDef *i2c, struct rt_i2c_msg *m, int sa)
{
    int ret = -1;
    int len = m->len;
    uint8_t *d = m->buf;

    I2C_GenerateSTART(i2c, ENABLE);
    rt_thread_mdelay(1);
    if (I2C_CheckEvent(i2c, I2C_EVENT_MASTER_MODE_SELECT) != SUCCESS)
    {
        goto out;
    }

    if (sa)
    {
        I2C_Send7bitAddress(i2c, m->addr << 1, I2C_Direction_Transmitter);
        rt_thread_mdelay(1);
        if (I2C_CheckEvent(i2c, I2C_EVENT_MASTER_TRANSMITTER_MODE_SELECTED) != SUCCESS)
        {
            goto out;
        }
    }

    while (len)
    {
        int cnt = 1000;

        I2C_SendData(i2c, *d);

        while (1)
        {
            if (I2C_CheckEvent(i2c, I2C_EVENT_MASTER_BYTE_TRANSMITTED) == SUCCESS)
                break;

            if (cnt-- < 0)
            {
                goto out;
            }
        }

        d++;
        len--;
    }

    ret = 0;

out:
    return ret;
}

static int iic_recv(I2C_TypeDef *i2c, struct rt_i2c_msg *m, int sa)
{
    int ret = -1;
    int len = m->len;
    uint8_t *d = m->buf;

    I2C_GenerateSTART(i2c, ENABLE);
    rt_thread_mdelay(1);
    if (I2C_CheckEvent(i2c, I2C_EVENT_MASTER_MODE_SELECT) != SUCCESS)
    {
        goto out;
    }

    //if (sa)
    {
        I2C_Send7bitAddress(i2c, m->addr << 1, I2C_Direction_Receiver);
        rt_thread_mdelay(1);
        if (I2C_CheckEvent(i2c, I2C_EVENT_MASTER_RECEIVER_MODE_SELECTED) != SUCCESS)
        {
            goto out;
        }
    }

    I2C_AcknowledgeConfig(i2c, ENABLE);

    while (len)
    {
        int cnt = 1000;

        if (len == 1)
            I2C_AcknowledgeConfig(i2c, DISABLE);

        while (1)
        {
            if (I2C_CheckEvent(i2c, I2C_EVENT_MASTER_BYTE_RECEIVED) == SUCCESS)
                break;

            if (cnt-- < 0)
            {
                goto out;
            }
        }

        *d = I2C_ReceiveData(i2c);

        d++;
        len--;
    }

    ret = 0;

out:
    return ret;
}

static rt_size_t _i2c_mst_xfer(struct rt_i2c_bus_device *bus,
                               struct rt_i2c_msg msgs[],
                               rt_uint32_t num)
{
    int n;
    struct rt_i2c_msg *m = msgs;
    di2c_t *di = (di2c_t *)bus;

    for (n = 0; n < num; n++, m++)
    {
        int ret;

        if (!(m->flags & RT_I2C_RD))
            ret = iic_send(di->i2c, m, n==0);
        else
            ret = iic_recv(di->i2c, m, 1);

        if (ret != 0)
            break;
    }

    I2C_GenerateSTOP(di->i2c, ENABLE);

    return n;
}

static rt_err_t _i2c_bus_control(struct rt_i2c_bus_device *bus,
                                 rt_uint32_t cmd,
                                 rt_uint32_t arg)
{
    return 0;
}

static const struct rt_i2c_bus_device_ops _i2c_ops = {
    .master_xfer = _i2c_mst_xfer,
    .slave_xfer = 0,
    .i2c_bus_control = _i2c_bus_control,
};

#ifdef BSP_USING_I2C1
static di2c_t _i2c1 = {
    .i2c = I2C1,
};
#endif

int i2c_drv_init(void)
{
#ifdef BSP_USING_I2C1
    _i2c1.busdev.ops = &_i2c_ops;
    iic1_init();
    rt_i2c_bus_device_register(&_i2c1.busdev, "i2c1");
#endif

    return 0;
}
INIT_BOARD_EXPORT(i2c_drv_init);
